﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using FCNS.Data.Table;
using DoubleH.Plugins;
using DoubleH.Utility;
using DoubleH.Utility.Configuration;
using System.Diagnostics;
using System.Xml;
using Table = FCNS.Data.Table;
using FCNS.Data;

namespace DoubleH
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            Table.ErrorS.BeginWriteError += (message) => { SqlError se = new SqlError(); se.Init(message); se.Show(); };

            InitVar();
            InitEvent();
            UpdateSoft();
        }

        private void UpdateSoft()
        {
            if (!DoubleHConfig.AppConfig.CheckUpdate)
                return;

            string oldVer = labelVersion.Content.ToString().Remove(0, 6);
            Func<string, string, string> func = DoubleH.Utility.IO.FileTools.CheckVerByAssembly;
            string str = func.Invoke(DbDefine.updateUrl, oldVer);
            if (!string.IsNullOrEmpty(str))
            {
                labelContact.Content = "新版本：" + str + " 已发布，请下载更新。";
                labelContact.Foreground = Brushes.Red;
            }
        }

        private void InitVar()
        {
            //初始化数据库
            if (DoubleHConfig.AppConfig.DataConfigItems.Count == 0)
            {
                DoubleHConfig.AppConfig.DataConfigItems.Add(new DataConfig()
                {
                    DataType = FCNS.Data.DataType.SQLITE.ToString(),
                    Flag = FCNS.Data.DataType.SQLITE.ToString(),
                    DataAddress = FCNS.Data.DbDefine.dbFile
                });
            }
            comboBoxData.ItemsSource = DoubleHConfig.AppConfig.DataConfigItems;
            comboBoxData.DisplayMemberPath = "Flag";
            comboBoxData.Text = DoubleHConfig.AppConfig.DataFlag;

            try { InitSqlData(); }
            catch (Exception ee) { Table.ErrorS.WriteLogFile("数据库连接错误 -> " + ee.Message); }

            comboBoxName.DisplayMemberPath = "_LoginName";
            comboBoxName.SelectedValuePath = "Password";

            this.Title = FCNS.Data.DbDefine.SystemName + " - 用户登录";
            comboBoxName.Text = DoubleHConfig.AppConfig.LastName;
            labelDbVer.Content += FCNS.Data.DbDefine.dbVer;

            string verNow = this.GetType().Assembly.GetName().Version.ToString();
            FileVersionInfo info = FileVersionInfo.GetVersionInfo(DbDefine.baseDir + "DoubleH.exe");
            labelVersion.Content += (verNow.Remove(verNow.Length - 1) + info.FileMinorPart.ToString() + info.FileBuildPart.ToString() + info.FilePrivatePart.ToString());

            textBoxPwd.Focus();
            this.Height = 265;
        }

        private void InitEvent()
        {
            labelHand.MouseMove += (ss, ee) =>
                {
                    double x = Mouse.GetPosition(labelHand).X;
                    double w = this.Width / 2;
                    this.Cursor = (x < w - 10 || x > w + 10) ? Cursors.Arrow : Cursors.Hand;
                };
            labelHand.MouseDoubleClick += (ss, ee) =>
            {
                if (!groupBoxDataFlag.IsEnabled && this.Cursor == Cursors.Hand)
                    InitSetSqlData();
            };
            labelHand.MouseLeave += (ss, ee) => this.Cursor = Cursors.Arrow;


            this.Closed += (ss, ee) => ConfigSerializer.SaveConfig(DoubleHConfig.AppConfig, DbDefine.appConfigFile);

            comboBoxData.SelectionChanged += (ss, ee) =>
            {
                DoubleHConfig.AppConfig.DataFlag = ((DataConfig)comboBoxData.SelectedItem).Flag;
                Application.Current.Shutdown();
                System.Diagnostics.Process.Start("DoubleH.exe");
            };

            labelContact.MouseUp += (ss, ee) => System.Diagnostics.Process.Start(DbDefine.webSite);
            labelVersion.MouseDoubleClick += (ss, ee) => ShowSql();

            textBoxPwd.KeyDown += (ss, ee) =>
                {
                    if (ee.Key == Key.Enter)
                        UserLogin();
                };

            buttonLogin.Click += (ss, ee) => UserLogin();
        }

        private void InitSqlData()
        {
            if (comboBoxData.SelectedItem == null)
                comboBoxData.SelectedIndex = 0;

            DataConfig dc = comboBoxData.SelectedItem as DataConfig;
            if (dc == null)
            {
                MessageWindow.Show("数据库配置错误");
                Table.ErrorS.WriteLogFile("数据库配置错误");
                this.Close();
            }
            FCNS.Data.SQLdata.SqlConfig = new FCNS.Data.SQLdata.SqlString()
            {
                DataType = (FCNS.Data.DataType)Enum.Parse(typeof(FCNS.Data.DataType), dc.DataType),
                Db = dc.DataName,
                IPorName = dc.DataAddress,
                Port = dc.Port,
                Password = dc.DataPassword,
                User = dc.DataUser
            };
            comboBoxName.ItemsSource = UserS.GetList(UserS.EnumEnable.启用, UserS.EnumFlag.操作员);
        }

        private void InitSetSqlData()
        {
            groupBoxDataFlag.IsEnabled = true;
            this.Height = 412;

            comboBoxDataType.ItemsSource = Enum.GetNames(typeof(DataType));

            listBoxFlag.ItemsSource = DoubleHConfig.AppConfig.DataConfigItems;
            listBoxFlag.DisplayMemberPath = "Flag";
            listBoxFlag.SelectedItem = DoubleHConfig.AppConfig.DataFlag;
            listBoxFlag.SelectionChanged += (ss, ee) =>
                {
                    if (listBoxFlag.SelectedItem == null)
                        return;

                    DataConfig dc = (DataConfig)listBoxFlag.SelectedItem;
                    textBoxFlag.Text = dc.Flag;
                    comboBoxDataType.Text = dc.DataType;
                    textBoxIpOrName.Text = dc.DataAddress;
                    integerUpDownPort.Value = Convert.ToInt32(dc.Port);
                    textBoxFile.Text = dc.DataName;
                    textBoxName.Text = dc.DataUser;
                    passwordBoxPwd.Password = dc.DataPassword;
                };

            buttonDelete.Click += (ss, ee) =>
                {
                    if (listBoxFlag.SelectedItem == null)
                        return;
                    if (MessageWindow.Show("", "确定要移除选择的项目吗?", MessageBoxButton.YesNo) == MessageBoxResult.No)
                        return;
                    DoubleHConfig.AppConfig.DataConfigItems.Remove((DataConfig)listBoxFlag.SelectedItem);
                };

            buttonNew.Click += (ss, ee) => DoubleHConfig.AppConfig.DataConfigItems.Add(new DataConfig() { Flag = "未命名数据库连接" });
            buttonSave.Click += (ss, ee) =>
                {
                    if (listBoxFlag.SelectedItem == null)
                        return;

                    DataConfig dc = (DataConfig)listBoxFlag.SelectedItem;
                    dc.Flag = textBoxFlag.Text;
                    dc.DataType = comboBoxDataType.Text;
                    dc.DataAddress = textBoxIpOrName.Text;
                    dc.Port = integerUpDownPort.Value.Value.ToString();
                    dc.DataName = textBoxFile.Text;
                    dc.DataUser = textBoxName.Text;
                    dc.DataPassword = passwordBoxPwd.Password;
                };
        }


        private void UserLogin()
        {
            if (SysConfig.SysConfigParams.Ver != FCNS.Data.DbDefine.dbVer)
            {
                if (MessageWindow.Show("数据库版本不一致,禁止登陆.", "是否下载更新补丁?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    System.Diagnostics.Process.Start(DbDefine.webSite);

                return;
                //DoubleH.Utility.Update.UpdateUtility uu = new Utility.Update.UpdateUtility();
            }

            if (string.IsNullOrEmpty(comboBoxName.Text))
            {
                MessageWindow.Show("请选择用户");
                return;
            }

            if ((string)comboBoxName.SelectedValue != textBoxPwd.Password)
            {
                MessageWindow.Show("用户名或密码错误");
                textBoxPwd.Clear();
                textBoxPwd.Focus();
                return;
            }

            DoubleHConfig.AppConfig.LastName = comboBoxName.Text;
            DoubleHConfig.AppConfig.DataFlag = comboBoxData.Text;
            textBoxPwd.Clear();//清空,当用户注销的时候就看不到密码了
            UserS.LoginUser = (UserS)comboBoxName.SelectedItem;
            DoubleHConfig.UserConfig = ConfigSerializer.LoadUserConfig(UserS.LoginUser.Id);
            WorkArea workArea = new WorkArea();
            workArea.Title = FCNS.Data.DbDefine.SystemName;
            workArea.loginUser.Content = "【当前登录用户:" + UserS.LoginUser.Name + "】";
            workArea.Closed += (s, ee) =>
            {
                workArea.PluginManager.UnloadAllExtension();
                ConfigSerializer.SaveConfig(DoubleHConfig.UserConfig, UserS.LoginUser.Id);
                if (workArea.CloseMe)
                    this.Close();
                else
                {
                    workArea.Clear();
                    workArea.Close();
                    this.Show();
                }
            };
            workArea.Show();

            this.Hide();
        }

        private void ShowSql()
        {
            SqlWindow sw = new SqlWindow();
            sw.ShowDialog();
        }

        private void ShowSysInfo()
        {
            StringBuilder sb = new StringBuilder("序列号:");
            try
            {
                sb.Append("kc" + FCNS.Data.SQLdata.ExecuteScalar("select count(*) from ProductSIO").ToString());
                sb.Append("pos" + FCNS.Data.SQLdata.ExecuteScalar("select count(*) from PosOrderS").ToString());
                sb.Append("sh" + FCNS.Data.SQLdata.ExecuteScalar("select count(*) from AfterSaleServiceS").ToString());
                sb.Append("car" + FCNS.Data.SQLdata.ExecuteScalar("select count(*) from CarS").ToString());
                sb.Append("\r\n");
            }
            catch
            {
                sb.Append("数据库连接失败");
            }
            MessageWindow.Show(sb.ToString());
        }
    }
}